import { getStore, setStore } from "@/util/store";
import {
  getUserInfo,
  loginByMobile,
  loginBySocial,
  loginByUsername,
  logout,
  refreshToken
} from "@/api/login";
import { deepClone, encryption } from "@/util/util";
import webisteOrigin from "@/const/website";
import { GetMenu } from "@/api/admin/menu";
// import router from "@/router/router";
// import dashboardRouter from "@/router/page/dashboard/index";
let webiste = deepClone(webisteOrigin);

const user = {
  state: {
    userInfo: getStore({ name: "userInfo" }) || {
      name: ""
    },
    permissions: getStore({ name: "permissions" }) || {},
    roles: getStore({ name: "roles" }) || [],
    themeColor: getStore({ name: "themeColor" }) || webiste.themeColor,
    themeName: getStore({ name: "themeName" }) || webiste.themeName,
    layout: getStore({ name: "layout" }) || "",
    project: getStore({ name: "project" }) || {},
    system_list: getStore({ name: "system_list" }) || [],
    system: getStore({ name: "system" }) || {},
    menu: getStore({ name: "menu" }) || [],
    menuAll: [],
    expires_in: getStore({ name: "expires_in" }) || "",
    access_token: getStore({ name: "access_token" }) || "",
    refresh_token: getStore({ name: "refresh_token" }) || "",
    tenant: getStore({ name: "tenant" }) || {},
    isShowPrj: false,
    sibar_status: {},
    needMenberShow: false, // 登陆是否需要显示选择系统
    currentUser: {}, // 设置当前用户包括token不需要持久化
    systemCode: getStore({ name: "systemCode" }) || 1, // 当前系统编码 1 珠江 2 投管
    systemInfo: getStore({ name: "systemInfo" }) || {}, // 系统信息
    systemList: getStore({ name: "systemList"}) || [] // 单点的list
  },
  actions: {
    // 根据用户名登录
    LoginByUsername({ commit }, userInfo) {
      const user = encryption({
        data: userInfo,
        key: "gdprgdprgdprgdpr",
        param: ["password"]
      });
      return new Promise((resolve, reject) => {
        loginByUsername(user.username, user.password, user.code, user.randomStr)
          .then(response => {
            const data = response.data;
            commit("SET_ACCESS_TOKEN", data.access_token);
            commit("SET_REFRESH_TOKEN", data.refresh_token);
            commit("SET_EXPIRES_IN", data.expires_in);
            commit("CLEAR_LOCK");
            console.log(data.access_token);
            resolve();
          })
          ["catch"](error => {
            reject(error);
          });
      });
    },
    // 根据手机号登录
    LoginByPhone({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginByMobile(userInfo.mobile, userInfo.code)
          .then(response => {
            const data = response.data;
            commit("SET_ACCESS_TOKEN", data.access_token);
            commit("SET_REFRESH_TOKEN", data.refresh_token);
            commit("SET_EXPIRES_IN", data.expires_in);
            commit("CLEAR_LOCK");
            resolve();
          })
          ["catch"](error => {
            reject(error);
          });
      });
    },
    // 根据OpenId登录
    LoginBySocial({ commit }, param) {
      return new Promise((resolve, reject) => {
        loginBySocial(param.state, param.code)
          .then(response => {
            const data = response.data;
            commit("SET_ACCESS_TOKEN", data.access_token);
            commit("SET_REFRESH_TOKEN", data.refresh_token);
            commit("SET_EXPIRES_IN", data.expires_in);
            commit("CLEAR_LOCK");
            resolve();
          })
          ["catch"](error => {
            reject(error);
          });
      });
    },
    GetUserInfo({ commit }, params) {
      return new Promise((resolve, reject) => {
        getUserInfo(params).then(res => {
          const data = res.data.data || {};
          commit("SET_USER_INFO", data.sysUser || {});
          commit("SET_ROLES", data.roles || []);
          commit("SET_PERMISSIONS", data.permissions || []);
          commit(
            "SET_THEME_NAME",
            (data.theme && data.theme.name) || webiste.themeName
          );
          commit(
            "SET_THEME_COLOR",
            (data.theme && JSON.parse(data.theme.value)) || webiste.themeColor
          );
          commit("SET_LAYOUT", data.layout || "");
          commit("SET_SYSTEM", data.system || {});
          commit("SET_TENANT", data.tenant || {});
          resolve(data);
        });
      });
    },
    // 刷新token
    RefreshToken({ commit, state }) {
      return new Promise((resolve, reject) => {
        refreshToken(state.refresh_token)
          .then(response => {
            const data = response.data;
            commit("SET_ACCESS_TOKEN", data.access_token);
            commit("SET_REFRESH_TOKEN", data.refresh_token);
            commit("SET_EXPIRES_IN", data.expires_in);
            commit("CLEAR_LOCK");
            resolve();
          })
          ["catch"](error => {
            reject(error);
          });
      });
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit("SET_MENU", []);
            commit("SET_PERMISSIONS", []);
            commit("SET_USER_INFO", {});
            commit("SET_ACCESS_TOKEN", "");
            commit("SET_REFRESH_TOKEN", "");
            commit("SET_EXPIRES_IN", "");
            commit("SET_ROLES", []);
            // commit("SET_TAG", {});
            // commit("DEL_ALL_TAG");
            commit("CLEAR_LOCK");
            commit("SET_THEME_COLOR", webiste.themeColor);
            commit("SET_THEME_NAME", webiste.themeName);
            commit("SET_CURRENTUSER", {});
            commit("SET_NEED_MENBER", false);
            commit("SET_SYSTEM_INFO", {});
            commit("SET_SYSTEM_INFO", {});
            commit("SET_SYS_AUTH_SYSTEM", []);
            console.log("xxx");
            resolve();
          })
          ["catch"](error => {
            reject(error);
          });
      });
    },
    // 注销session
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_MENU", []);
        commit("SET_PERMISSIONS", []);
        commit("SET_USER_INFO", {});
        commit("SET_ACCESS_TOKEN", "");
        commit("SET_REFRESH_TOKEN", "");
        commit("SET_ROLES", []);
        commit("SET_TAG", {});
        commit("DEL_ALL_TAG");
        commit("CLEAR_LOCK");
        commit("SET_THEME_COLOR", webiste.themeColor);
        commit("SET_THEME_NAME", webiste.themeName);
        commit("SET_CURRENTUSER", {});
        commit("SET_NEED_MENBER", false);
        commit("SET_SYSTEM_INFO", {});
        resolve();
      });
    },
    // 获取系统菜单
    GetMenu({ commit, state }, type = "portal") {
      return new Promise(resolve => {
        GetMenu({ systemCode: type }).then(res => {
          if (res.data.code === 0) {
            let resData = res.data.data;
            console.log(resData);
            // 系统列表
            commit("SET_SYSTEM_LIST", resData);
            // 设置默认选中的系统(默认系统是否有设置，没有则使用第一个)
            let length = Object.keys(state.system).length;
            console.log(state.system);
            let defaulSystemId = state.system.id || "";
            if (!length || length <= 0) {
              commit("SET_SYSTEM", resData[0]);
              defaulSystemId = resData[0].id;
            }
            // 设置默认展开的菜单
            resData.forEach((item, index) => {
              if (item.id === defaulSystemId) {
                console.log(resData[index].children);
                commit("SET_MENU", resData[index].children);
                // commit("SET_MENU", [{ name: "xx", label: "xxxss" }]);
              }
            });
            // console.log(router);
            // console.log(state.menu);
            // state.menu = menu;
            // router.addRoutes([dashboardRouter]);
            resolve(resData);
          } else {
            console.log("获取菜单数据失败");
          }
        });
      });
    }
  },
  mutations: {
    // 设置当前系统信息 例如 logo text
    SET_SYSTEM_INFO(state, info) {
      state.systemInfo = info;
      console.log(info);
      setStore({
        name: "systemInfo",
        content: state.systemInfo,
        type: "session"
      });
    },
    // 设置当前单点的地址
    SET_SYS_AUTH_SYSTEM(state, info) {
      state.systemList = info.map(v => {
        let json = {
          ...v,
          authUrl: v.authUrl + state.access_token
        };
        return json;
      });
      console.log(state.systemList);
      setStore({
        name: "systemList",
        content: state.systemList,
        type: "session"
      });
    },
    // 设置当前系统编码
    SET_SYSITEM_CODE(state, code) {
      state.systemCode = code;
      setStore({
        name: "systemCode",
        content: state.systemCode,
        type: "session"
      });
    },
    SET_CURRENTUSER(state, data) {
      // 设置当前用户不需要持久化
      state.currentUser = data;
    },
    SET_NEED_MENBER(state, data) {
      state.needMenberShow = data;
    },
    SET_IS_SHOW_PRJ: (state, status) => {
      state.isShowPrj = status;
    },
    SET_SIBAR_STATUS: (state, status) => {
      state.sibar_status = status;
    },
    SET_ACCESS_TOKEN: (state, access_token) => {
      state.access_token = access_token;
      setStore({
        name: "access_token",
        content: state.access_token,
        type: "session"
      });
    },
    SET_EXPIRES_IN: (state, expires_in) => {
      state.expires_in = expires_in;
      setStore({
        name: "expires_in",
        content: state.expires_in,
        type: "session"
      });
    },
    SET_REFRESH_TOKEN: (state, rfToken) => {
      state.refresh_token = rfToken;
      setStore({
        name: "refresh_token",
        content: state.refresh_token,
        type: "session"
      });
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
      setStore({
        name: "userInfo",
        content: userInfo,
        type: "session"
      });
    },
    SET_MENU: (state, menu) => {
      state.menu = menu;
      setStore({
        name: "menu",
        content: menu,
        type: "session"
      });
    },
    SET_MENU_ALL: (state, menuAll) => {
      state.menuAll = menuAll;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
      setStore({
        name: "roles",
        content: roles,
        type: "session"
      });
    },
    SET_PERMISSIONS: (state, permissions) => {
      const list = {};
      for (let i = 0; i < permissions.length; i++) {
        list[permissions[i]] = true;
      }
      state.permissions = list;
      setStore({
        name: "permissions",
        content: state.permissions,
        type: "session"
      });
    },
    SET_THEME_COLOR: (state, themeColor) => {
      state.themeColor = themeColor;
      setStore({
        name: "themeColor",
        content: state.themeColor,
        type: "session"
      });
    },
    SET_THEME_NAME: (state, themeName) => {
      state.themeName = themeName;
      setStore({
        name: "themeName",
        content: state.themeName,
        type: "session"
      });
    },
    SET_LAYOUT: (state, layout) => {
      state.layout = layout;
      console.log(state.layout);
      setStore({
        name: "layout",
        content: state.layout,
        type: "session"
      });
    },
    SET_PROJECT: (state, project) => {
      state.project = project;
      setStore({
        name: "project",
        content: project,
        type: "session"
      });
    },
    SET_SYSTEM_LIST: (state, system_list) => {
      state.system_list = system_list;
      setStore({
        name: "system_list",
        content: system_list,
        type: "session"
      });
      console.log(state.system_list);
    },
    SET_SYSTEM: (state, system) => {
      state.system = system;
      setStore({
        name: "system",
        content: system,
        type: "session"
      });
    },
    SET_TENANT: (state, tenant) => {
      state.tenant = tenant;
      setStore({
        name: "tenant",
        content: tenant,
        type: "session"
      });
    }
  }
};
export default user;
